﻿using HAF.Core.Datas;
using HAF.Dispatcher.WorkItem;
using HAF.LogUtility;
using HAF.LogUtility.Assistantor;
using RDS.Core;
using RDSEngine.Filters;
using RDSEngine.WorkItems;
using System;
using System.Web.Http;

namespace RDSEngine.Controllers
{
    //[RoutePrefix("api/down")]
    public class DownController : ApiController
    {
        private void ShowMessage(string msg)
        {
            LogHelper.WriteDebugLog(msg);
            RuntimeAdapter.ShowConsol?.Invoke(msg);
        }
        
        /// <summary>
        /// 获取任务执行状态
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        public IHttpActionResult Get(string tid)
        {
            RdsReturnJson returnJson = new RdsReturnJson() { Statu = -1, Comment = "失败", ReturnValues = null };
            if (!string.IsNullOrEmpty(tid) && RuntimeAdapter.Tasks != null && RuntimeAdapter.Tasks.Exists(t=> t.ID == tid))
            {
                var task = RuntimeAdapter.Tasks.Find(t => t.ID == tid);
                if (task != null)
                {
                    TaskResponse returnTask = new TaskResponse()
                    {
                        TaskID = task.ID,
                        Statu = (int)task.State,
                        Comment = task.State.ToString()
                    };
                    returnJson.Statu = 1;
                    returnJson.Comment = "成功";
                    returnJson.ReturnValues = returnTask;
                }
            }
            else
            {
                returnJson.Comment = "失败，未查询到当前任务";
            }

            return Json(returnJson);
        }

        //[Route("get")]
        //[HttpGet]
        //public IHttpActionResult Get()
        //{
        //    return Ok("Hello World!");
        //}

        [LogFilter]
        [HttpPost]
        public IHttpActionResult Post([FromBody]Object value)
        {
            //获取客户端IP地址
            string clientIP = HttpRequestMessageExtensions.GetClientIpAddress(Request);
            ShowMessage(string.Format("金沙引擎：接收到来自{0}的资源下载请求", clientIP));

            if (value != null)
            {
                RequestTask task = JsonAssistant.Deserialize<RequestTask>(value.ToString());
                if (task == null)
                {
                    ShowMessage("请求参数获取异常");
                    return Json(new RdsReturnJson() { Statu = -1, Comment = "请求参数获取异常！", ReturnValues = null });
                }
                else
                {
                    ShowMessage(string.Format("接收到{0}的资源处理请求，请求内容为：{1}", clientIP, value.ToString().Replace("\r\n","")));
                    bool isTaskExsits = false;
                    //任务排重
                    if (RuntimeAdapter.Tasks.Exists(t=>t.ID == task.ID))
                    {
                        var tt = RuntimeAdapter.Tasks.Find(t => t.ID == task.ID);
                        //正在执行中的任务重复注入将被拒绝
                        if (tt.State > 0 && tt.State < 5 )
                        {
                            return Json(new RdsReturnJson() { Statu = -1, Comment = "失败：任务编号重复", ReturnValues = null });
                        }
                        else
                        {
                            isTaskExsits = true;
                            tt.State = 1;
                        }
                        //TO-DO:失败的任务，二次请求怎么处理？
                    }
                    //加载插件
                    if (RuntimeAdapter.RunPugins != null && RuntimeAdapter.RunPugins.Plugins != null)
                    {
                        WorkPlugin runItem = RuntimeAdapter.RunPugins.Plugins.Find(t => t.Tag.ToLower() == task.Type.ToLower());
                        if (runItem != null)
                        {
                            //添加到任务库
                            if (!isTaskExsits) RuntimeAdapter.Tasks.Add(new RunTask() { ID = task.ID, Type = task.Type, State = 0, CreateTime = DateTime.Now });
                            //加载外部插件库
                            LoadWorker.GetInstance().LoadAssembly(runItem.LoadPluginFile);
                            //List<object> tmpTasks = new List<object>();
                            //if (task.Task is JArray)
                            //{
                            //    tmpTasks = (task.Task as JArray).ToObject<List<object>>();
                            //    ShowMessage("-----------------");
                            //}
                            //执行插件内部方法（默认为Regist动作）
                            //bool rtn = LoadWorker.GetInstance().Invoke(runItem.LoadClass, "Regist", task.ID, tmpTasks);
                            bool rtn = LoadWorker.GetInstance().Invoke(runItem.LoadClass, "Regist", task.ID, task.Task);
                            if (!rtn)
                            {
                                return Json(new RdsReturnJson() { Statu = -1, Comment = "失败：程序内部异常", ReturnValues = null });
                            }
                            ShowMessage(string.Format("添加下载任务{0}到执行队列完成", task.ID));
                        }
                    }

                }
                ShowMessage(string.Format("同步回馈{0}请求", clientIP));
                return Json(new RdsReturnJson() { Statu = 1, Comment = "成功", ReturnValues = null });
            }
            else
            {
                return Json(new RdsReturnJson() { Statu = -1, Comment = "失败：请求参数为空", ReturnValues = null });
            }
        }

        /// <summary>  
        /// 获取当前时间戳  
        /// </summary>  
        /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.</param>  
        /// <returns></returns>  
        private string GetTimeStamp(bool bflag = true)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string ret = string.Empty;
            if (bflag)
                ret = Convert.ToInt64(ts.TotalSeconds).ToString();
            else
                ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();

            return ret;
        }
        // PUT api/values/5 
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5 
        public void Delete(int id)
        {
        }
    }
}
